<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <!--      <el-input clearable @clear="load" style="width: 260px;" v-model="data.username" placeholder="请输入账号查询"-->
      <!--                prefix-icon="Search"></el-input>-->
      <el-input clearable @clear="load" style="width: 200px;margin-left: 5px" v-model="data.name"
                placeholder="请输入名称查询" prefix-icon="Search"></el-input>
      <el-select
          v-model="data.selectedClass"
          placeholder="请选择班级"
          style="width: 150px; margin-left: 10px"
          clearable
      >
        <el-option
            value="all"
            label="所有班级"
            :key="'all-option'"
        />
        <el-option
            v-for="cls in data.classOptions"
            :key="cls"
            :label="cls"
            :value="cls"
        />
      </el-select>
      <el-button type="primary" style="margin-left: 5px" @click="load">查 询</el-button>
      <el-button type="info" style="margin-left: 5px" @click="reset">重 置</el-button>
      <el-button v-if="data.user.role==='USER'" type="info" style="background-color: #7e55fc;margin-left: 5px" @click="exportData">批量导出
      </el-button>
      <el-button
          type="success"
          style="margin-left: 5px"
          @click="setDefaultClass"
      >
        设为默认班级
      </el-button>

      <!-- 提示信息 -->
      <el-tooltip
          v-if="data.defaultClass"
          :content="tooltipContent"
          placement="top"
      >
        <span class="default-class-indicator"><el-icon><Warning/></el-icon></span>
      </el-tooltip>
    </div>
    <div class="card" style="margin-bottom: 5px" v-if="data.user.role==='ADMIN'">
      <el-button type="primary" @click="handleAdd" >新 增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      <el-upload style="display: inline-block;margin-left: 10px"
                 :action="`${BASE_URL}/students/import`"
                 :show-file-list="false"
                 :before-upload="beforeExcelUpload"
                 :on-success="handleImportSuccess"
                 accept=".xls,.xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
        <el-button type="success" :loading="isUploading">批量导入</el-button>
      </el-upload>
      <el-button type="info" style="background-color: #7e55fc;margin-left: 10px" @click="exportData">批量导出
      </el-button>
      <el-button type="danger" style="margin-left: 10px" @click="clearAllData">清空数据
      </el-button>
    </div>

    <div class="card" style="margin-bottom: 5px; width: 100%;">
      <el-table max-height="500"
          :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
          :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="className" label="班级"/>
        <el-table-column prop="name" label="姓名"/>
        <el-table-column prop="studentNumber" label="学号"/>
        <el-table-column prop="seatNumber" label="座号"/>
        <el-table-column label="操作" width="100px">
          <template #default="scope">
            <el-button type="primary" icon="edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="delete" circle @click="del(scope.row.studentId)"></el-button>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total,sizes, prev, pager, next,jumper"
          :page-sizes="[5,10, 20, 30, 40, 50, 100]"
          :total="data.total"
          @size-change="load"
          @current-change="load"/>
    </div>

    <el-dialog v-model="data.adminFormVisible" title="学生信息" width="500" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="80px"
               style="padding: 20px 30px 20px 0">
        <el-form-item prop="name" label="姓名">
          <el-input v-model="data.form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="className" label="班级">
          <el-input v-model="data.form.className" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="studentNumber" label="学号">
          <el-input v-model="data.form.studentNumber" autocomplete="off"/>
        </el-form-item>
        <el-form-item prop="seatNumber" label="座号">
          <el-input v-model="data.form.seatNumber" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.adminFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import request from "@/utils/request";
import {computed, onMounted, reactive, ref} from "vue";
import {ElLoading, ElMessage, ElMessageBox, ElNotification} from "element-plus";

const BASE_URL = import.meta.env.VITE_API_BASE_URL;
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"),
  name: null,
  selectedClass: localStorage.getItem('defaultClass') || '',
  defaultClass: '',
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  adminFormVisible: false,
  form: {},
  rules: {
    name: [{required: true, message: '请填写姓名', trigger: 'blur'}],
    className: [{required: true, message: '请填写班级', trigger: 'blur'}],
    studentNumber: [{required: true, message: '请填写学号', trigger: 'blur'}],
    seatNumber: [{required: true, message: '请填写座号', trigger: 'blur'}],
  },
  rows: [],
  classOptions: []
})
// 使用计算属性动态生成提示内容
const tooltipContent = computed(() => {
  return `当前默认班级: ${data.defaultClass}`;
});
onMounted(() => {
  load()
  fetchClasses()
});
const load = () => {
  request.get('/students/page', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name?.trim(), // 增加trim()，避免空格导致的无效查询
      selectedClass: data.selectedClass,
    }
  }).then(res => {
    // console.log(res)
    if (res.code === '200') {
      // ElMessage.success('请求成功')
      data.tableData = res.data.records
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg || '加载学生列表失败');
    }
  })
}
const fetchClasses = () => {
  request.get('/students/getClasses').then(res => {
    if (res.code === '200') {
      data.classOptions = res.data;
      data.classOptions.sort((a, b) => Number(a) - Number(b));
    } else {
      ElMessage.error(res.msg || '加载班级列表失败');
    }
  })
}
const setDefaultClass = () => {
  data.defaultClass = data.selectedClass;
  localStorage.setItem('defaultClass', data.selectedClass);
  ElMessage.success(`已将 ${data.selectedClass} 设置为默认班级`);
}
const formRef = ref()

const reset = () => {
  data.name = null
  data.selectedClass = localStorage.getItem('defaultClass') || ''
  load()
}
// 添加功能
const handleAdd = () => {
  data.adminFormVisible = true
  data.form = {}
}

const add = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/students/add', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('新增成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))//深度拷贝数据
  // console.log(data.form)
  data.adminFormVisible = true
}

const update = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.put('/students/update', data.form).then(res => {
        if (res.code === '200') {
          data.adminFormVisible = false
          ElMessage.success('修改成功')
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
const save = () => {
  data.form.studentId ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/students/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const handleSelectionChange = (rows) => {
  data.rows = rows
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  // 只提取需要的ID列表，减少数据传输
  const ids = data.rows.map(row => row.studentId)
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.post('/students/deleteBatch', ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
  })
}

const exportData = () => {
  // 判断是否有选中的数据
  if (data.rows.length > 0) {
    // 导出选中的数据：提取选中项的ID，拼接成参数
    const ids = data.rows.map(item => item.studentId).join(',');
    const url = `${BASE_URL}/students/export?ids=${ids}`;
    window.open(url);
  } else {
    // 没有选中数据时，按原条件导出（按username筛选）
    let url = `${BASE_URL}/students/export?name=${data.name === null ? '' : data.name}`
    window.open(url);
  }
}
// 导入文件方法
const isUploading = ref(false);
let loadingInstance = null;
const closeLoading = () => {
  if (loadingInstance) {
    loadingInstance.close();
    loadingInstance = null;
  }
};
const beforeExcelUpload = (rawFile) => {
  // 创建加载提示
  loadingInstance = ElLoading.service({
    lock: true,
    text: '正在导入数据，请稍候...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  // 文件类型验证
  const isExcel =
      ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(rawFile.type) ||
      ['.xls', '.xlsx'].some(ext => rawFile.name.toLowerCase().endsWith(ext));

  if (!isExcel) {
    ElMessage.error('仅支持上传 .xls 或 .xlsx 格式的 Excel 文件!');
    closeLoading();
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error('文件大小不能超过10MB!')
    closeLoading();
    return false
  }
  isUploading.value = true;
  return true
}
const handleImportSuccess = (res) => {
  isUploading.value = false;
  closeLoading();
  if (res.code === '200') {
    ElMessage.success(res.data || '批量导入成功')
  } else {
    ElMessage.error(res.msg)
  }
  load()
}
const clearAllData = () => {
  ElMessageBox.confirm('删除后无法恢复，您确认删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/students/deleteAllData').then(res => {
      if (res.code === '200') {
        ElMessage.success('清除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    ElMessage.error('出错了')
  })
}
</script>

<style scoped>

</style>